import PositionController from '../controller/positionController';
import SearchController from '../controller/searchController';
import MyController from '../controller/myController';
import DetailController from "../controller/detailController";
import ErrorpageController from '../controller/errorpageController';

export default class Router {
    constructor(mode) {
        this.mode = mode;//使用哪种方式跳转 history/hash
        this.initEvent();

        this.routers = {
            "position": PositionController,
            "search": SearchController,
            "my": MyController,
            "detail": DetailController
        }
        new PositionController().render();
        this.loadView();
    }
    //加载视图
    loadView(path = "position") {//使用history跳转
        if (this.routers[path]) {
            new this.routers[path]().render();
        } else {
            new ErrorpageController().render();
        }
    }
    initEvent() {
        if (this.mode === "hash") {//用hash跳转，调用方法
            window.addEventListener("hashchange", () => {
                var hash = location.hash.replace('#', '');
                if (/details\//.test(hash)) {
                    var id = hash.split('/')[1];
                    hash = hash.split('/')[0];
                }
                this.loadView(hash);
            })
        } else {//匹配用history跳转，调用方法
            window.addEventListener('popstate', () => {
                let path = history.state ? history.state.url : undefined;
                this.loadView(path);
            })
        }

    }

}